package com.supermap.grpc;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

/**
 * @author liqs
 * @version 1.0
 * @date 2021/10/20 15:15
 * ref:https://blog.csdn.net/hzygcs/article/details/104729274/?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_title~default-1.no_search_link&spm=1001.2101.3001.4242.1
 */
public class HelloWorldServer {

    private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName());

    /* The port on which the server should run */
    private int port = 50051;
    private Server server;

    /**
     * Main launches the server from the command line.
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        final HelloWorldServer server = new HelloWorldServer();
        server.start();
        server.blockUntilShutdown();
    }

    private void start() throws IOException {

        /**
         * 可根据实际需要构造多个
         */
        GreeterImpl greeter = new GreeterImpl();
        GoImpl go = new GoImpl();

        server = ServerBuilder.forPort(port)
                .addService(greeter)
                .addService(go)
                .build()
                .start();
        logger.info("Server started, listening on " + port);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                // Use stderr here since the logger may have been reset by its JVM shutdown hook.
                System.err.println("*** shutting down gRPC server since JVM is shutting down");
                HelloWorldServer.this.stop();
                System.err.println("*** server shut down");
            }
        });
    }

    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    /**
     * Await termination on the main thread since the grpc library uses daemon threads.
     */
    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    private class GreeterImpl extends GreeterGrpc.GreeterImplBase {
        /** 原子Integer */
        public AtomicInteger count = new AtomicInteger(0);
        @Override
        public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
            System.out.println("call sayHello");
            HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName() + ", your sex is  " + req.getSex()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
            System.out.println(count.incrementAndGet() + Thread.currentThread().getName());
        }

    }

    private class GoImpl extends HelloGoGrpc.HelloGoImplBase {
        /** 原子Integer */
        public AtomicInteger count = new AtomicInteger(0);
        @Override
        public void sayHelloGo(HelloGoRequest request, StreamObserver<HelloGoReply> responseObserver) {
            System.out.println("call sayHelloGo");
            HelloGoReply helloGoReply = HelloGoReply.newBuilder().setMessage("Hello" + request.getName() + ", now you find go server").build();
            responseObserver.onNext(helloGoReply);
            responseObserver.onCompleted();
            System.out.println(count.incrementAndGet() + Thread.currentThread().getName());
        }
    }

}

